<template>
  <div class="realtime-demo">
    <div class="demo-header">
      <h1>🚀 实时动态数据演示</h1>
      <p>数据每秒自动更新，展示真实的监控效果</p>
      <div class="controls">
        <button @click="toggleAutoUpdate" :class="{ active: isAutoUpdating }">
          {{ isAutoUpdating ? '⏸️ 暂停更新' : '▶️ 开始更新' }}
        </button>
        <button @click="manualUpdate">🔄 手动刷新</button>
        <span class="update-counter">更新次数: {{ updateCount }}</span>
      </div>
    </div>

    <div class="demo-grid">
      <!-- 系统统计实时变化 -->
      <div class="demo-card">
        <h3>📊 系统统计数据</h3>
        <div class="stats-display">
          <div class="stat-item">
            <span class="label">在线瓷砖:</span>
            <span class="value" :class="getTrendClass(systemStats.onlineTiles.trend.type)">
              {{ systemStats.onlineTiles.value }}{{ systemStats.onlineTiles.unit }}
              <small>({{ systemStats.onlineTiles.trend.value }})</small>
            </span>
          </div>
          <div class="stat-item">
            <span class="label">异常信号:</span>
            <span class="value" :class="getTrendClass(systemStats.abnormalSignals.trend.type)">
              {{ systemStats.abnormalSignals.value }}{{ systemStats.abnormalSignals.unit }}
              <small>({{ systemStats.abnormalSignals.trend.value }})</small>
            </span>
          </div>
          <div class="stat-item">
            <span class="label">平均压力:</span>
            <span class="value" :class="getTrendClass(systemStats.averagePressure.trend.type)">
              {{ systemStats.averagePressure.value }}{{ systemStats.averagePressure.unit }}
              <small>({{ systemStats.averagePressure.trend.value }})</small>
            </span>
          </div>
          <div class="stat-item">
            <span class="label">今日信号:</span>
            <span class="value" :class="getTrendClass(systemStats.todaySignals.trend.type)">
              {{ formatNumber(systemStats.todaySignals.value) }}{{ systemStats.todaySignals.unit }}
              <small>({{ systemStats.todaySignals.trend.value }})</small>
            </span>
          </div>
        </div>
        <div class="system-status">
          <span class="status-label">系统状态:</span>
          <span class="status-value" :class="systemStats.systemStatus.status">
            {{ systemStats.systemStatus.text }}
          </span>
        </div>
      </div>

      <!-- 热图数据实时变化 -->
      <div class="demo-card">
        <h3>🌡️ 热图数据统计</h3>
        <div class="heatmap-stats" v-if="heatmapStats">
          <div class="stat-row">
            <span>总设备数:</span>
            <span>{{ heatmapStats.total }}</span>
          </div>
          <div class="stat-row">
            <span>正常设备:</span>
            <span class="normal">{{ heatmapStats.normal }}</span>
          </div>
          <div class="stat-row">
            <span>警告设备:</span>
            <span class="warning">{{ heatmapStats.warning }}</span>
          </div>
          <div class="stat-row">
            <span>严重设备:</span>
            <span class="critical">{{ heatmapStats.critical }}</span>
          </div>
          <div class="stat-row">
            <span>平均压力:</span>
            <span>{{ heatmapStats.avgPressure }} kPa</span>
          </div>
          <div class="stat-row">
            <span>压力范围:</span>
            <span>{{ heatmapStats.minPressure }} - {{ heatmapStats.maxPressure }} kPa</span>
          </div>
        </div>
      </div>

      <!-- 趋势数据实时变化 -->
      <div class="demo-card">
        <h3>📈 最新趋势数据</h3>
        <div class="trend-display" v-if="latestTrend">
          <div class="trend-item">
            <span class="label">当前时间:</span>
            <span class="value">{{ latestTrend.time }}</span>
          </div>
          <div class="trend-item">
            <span class="label">压力值:</span>
            <span class="value">{{ latestTrend.pressure }} kPa</span>
          </div>
          <div class="trend-item">
            <span class="label">告警数:</span>
            <span class="value">{{ latestTrend.alerts }}</span>
          </div>
          <div class="trend-item">
            <span class="label">在线设备:</span>
            <span class="value">{{ latestTrend.online }}</span>
          </div>
          <div class="trend-item">
            <span class="label">响应时间:</span>
            <span class="value">{{ latestTrend.responseTime }}ms</span>
          </div>
          <div class="trend-item">
            <span class="label">系统负载:</span>
            <span class="value">{{ latestTrend.systemLoad }}%</span>
          </div>
        </div>
      </div>

      <!-- 健康评分实时变化 -->
      <div class="demo-card">
        <h3>💚 健康评分</h3>
        <div class="health-display" v-if="healthScore">
          <div class="score-circle">
            <div class="score-value">{{ healthScore.score }}%</div>
            <div class="score-level">{{ healthScore.levelDescription }}</div>
          </div>
          <div class="factors">
            <div class="factor" v-for="(factor, key) in healthScore.factors" :key="key">
              <span class="factor-name">{{ factor.description }}:</span>
              <span class="factor-score" :class="getScoreClass(factor.score)">
                {{ factor.score }}分
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时变化日志 -->
      <div class="demo-card full-width">
        <h3>📝 实时变化日志</h3>
        <div class="change-log">
          <div 
            v-for="(log, index) in changeLogs" 
            :key="index" 
            class="log-entry"
            :class="log.type"
          >
            <span class="timestamp">{{ log.timestamp }}</span>
            <span class="message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import smartTileApi from '../api/smartTileApi.js'

export default {
  name: 'RealTimeDataDemo',
  data() {
    return {
      isAutoUpdating: false,
      updateCount: 0,
      updateTimer: null,
      
      // 数据存储
      systemStats: {
        onlineTiles: { value: 0, unit: '块', trend: { type: 'positive', value: '0%' } },
        abnormalSignals: { value: 0, unit: '处', trend: { type: 'negative', value: '0%' } },
        averagePressure: { value: 0, unit: 'kPa', trend: { type: 'negative', value: '0%' } },
        todaySignals: { value: 0, unit: '个', trend: { type: 'positive', value: '0%' } },
        systemStatus: { status: 'normal', text: '运行正常' }
      },
      heatmapStats: null,
      latestTrend: null,
      healthScore: null,
      
      // 变化日志
      changeLogs: [],
      previousData: {}
    }
  },
  
  mounted() {
    this.loadInitialData()
    // 自动开始实时更新
    this.toggleAutoUpdate()
  },
  
  beforeUnmount() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  
  methods: {
    async loadInitialData() {
      await this.updateAllData()
      this.storePreviousData()
    },
    
    async updateAllData() {
      try {
        // 并行获取所有数据
        const [statsResponse, heatmapResponse, trendResponse, healthResponse] = await Promise.all([
          smartTileApi.getSystemStats(),
          smartTileApi.getHeatmapData({ area: 'all' }),
          smartTileApi.getTrendData({ timeRange: 'today' }),
          smartTileApi.getHealthScore()
        ])
        
        // 更新数据
        if (statsResponse.success) {
          this.detectChanges('系统统计', this.systemStats, statsResponse.data)
          this.systemStats = statsResponse.data
        }
        
        if (heatmapResponse.success) {
          this.detectChanges('热图统计', this.heatmapStats, heatmapResponse.data.statistics)
          this.heatmapStats = heatmapResponse.data.statistics
        }
        
        if (trendResponse.success) {
          const latest = trendResponse.data.trend[trendResponse.data.trend.length - 1]
          this.detectChanges('趋势数据', this.latestTrend, latest)
          this.latestTrend = latest
        }
        
        if (healthResponse.success) {
          this.detectChanges('健康评分', this.healthScore, healthResponse.data)
          this.healthScore = healthResponse.data
        }
        
        this.updateCount++
        
      } catch (error) {
        console.error('更新数据失败:', error)
        this.addLog('error', '数据更新失败: ' + error.message)
      }
    },
    
    detectChanges(category, oldData, newData) {
      if (!oldData || !newData) return
      
      // 检测数值变化
      if (category === '系统统计') {
        if (oldData.onlineTiles.value !== newData.onlineTiles.value) {
          this.addLog('info', `在线瓷砖数变化: ${oldData.onlineTiles.value} → ${newData.onlineTiles.value}`)
        }
        if (oldData.abnormalSignals.value !== newData.abnormalSignals.value) {
          this.addLog('warning', `异常信号变化: ${oldData.abnormalSignals.value} → ${newData.abnormalSignals.value}`)
        }
        if (Math.abs(oldData.averagePressure.value - newData.averagePressure.value) > 0.1) {
          this.addLog('info', `平均压力变化: ${oldData.averagePressure.value} → ${newData.averagePressure.value}`)
        }
      }
      
      if (category === '健康评分' && oldData.score !== newData.score) {
        this.addLog('success', `健康评分变化: ${oldData.score}% → ${newData.score}%`)
      }
    },
    
    addLog(type, message) {
      const log = {
        type,
        message,
        timestamp: new Date().toLocaleTimeString('zh-CN')
      }
      
      this.changeLogs.unshift(log)
      
      // 保持最多50条日志
      if (this.changeLogs.length > 50) {
        this.changeLogs = this.changeLogs.slice(0, 50)
      }
    },
    
    storePreviousData() {
      this.previousData = {
        systemStats: JSON.parse(JSON.stringify(this.systemStats)),
        heatmapStats: JSON.parse(JSON.stringify(this.heatmapStats)),
        latestTrend: JSON.parse(JSON.stringify(this.latestTrend)),
        healthScore: JSON.parse(JSON.stringify(this.healthScore))
      }
    },
    
    toggleAutoUpdate() {
      if (this.isAutoUpdating) {
        clearInterval(this.updateTimer)
        this.updateTimer = null
        this.isAutoUpdating = false
        this.addLog('info', '自动更新已停止')
      } else {
        this.updateTimer = setInterval(() => {
          this.updateAllData()
        }, 1000) // 每秒更新
        this.isAutoUpdating = true
        this.addLog('success', '自动更新已开始 (每秒)')
      }
    },
    
    async manualUpdate() {
      this.addLog('info', '手动刷新数据...')
      await this.updateAllData()
    },
    
    getTrendClass(type) {
      return {
        'trend-positive': type === 'positive',
        'trend-negative': type === 'negative'
      }
    },
    
    getScoreClass(score) {
      if (score >= 90) return 'excellent'
      if (score >= 80) return 'good'
      if (score >= 70) return 'fair'
      return 'poor'
    },
    
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toLocaleString()
    }
  }
}
</script>

<style scoped>
.realtime-demo {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.demo-header {
  text-align: center;
  margin-bottom: 30px;
}

.demo-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.demo-header p {
  color: #7f8c8d;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.controls button {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.controls button:first-child {
  background: #e74c3c;
  color: white;
}

.controls button:first-child.active {
  background: #27ae60;
}

.controls button:nth-child(2) {
  background: #3498db;
  color: white;
}

.controls button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.update-counter {
  background: #34495e;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.demo-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  transition: transform 0.3s;
}

.demo-card:hover {
  transform: translateY(-2px);
}

.demo-card.full-width {
  grid-column: 1 / -1;
}

.demo-card h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  border-bottom: 2px solid #ecf0f1;
  padding-bottom: 8px;
}

.stats-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ecf0f1;
}

.stat-item .label {
  font-weight: 500;
  color: #34495e;
}

.stat-item .value {
  font-weight: bold;
  font-size: 16px;
}

.stat-item .value small {
  font-size: 12px;
  margin-left: 5px;
}

.trend-positive {
  color: #27ae60;
}

.trend-negative {
  color: #e74c3c;
}

.system-status {
  margin-top: 15px;
  padding: 10px;
  background: #ecf0f1;
  border-radius: 6px;
  text-align: center;
}

.status-value.normal {
  color: #27ae60;
  font-weight: bold;
}

.status-value.warning {
  color: #f39c12;
  font-weight: bold;
}

.status-value.critical {
  color: #e74c3c;
  font-weight: bold;
}

.heatmap-stats, .trend-display {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-row, .trend-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px solid #ecf0f1;
}

.normal { color: #27ae60; }
.warning { color: #f39c12; }
.critical { color: #e74c3c; }

.health-display {
  text-align: center;
}

.score-circle {
  margin-bottom: 20px;
}

.score-value {
  font-size: 36px;
  font-weight: bold;
  color: #2c3e50;
}

.score-level {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 5px;
}

.factors {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.factor {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px solid #ecf0f1;
}

.factor-name {
  font-size: 12px;
  color: #7f8c8d;
}

.factor-score.excellent { color: #27ae60; }
.factor-score.good { color: #2ecc71; }
.factor-score.fair { color: #f39c12; }
.factor-score.poor { color: #e74c3c; }

.change-log {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ecf0f1;
  border-radius: 6px;
  padding: 10px;
}

.log-entry {
  display: flex;
  gap: 10px;
  padding: 4px 0;
  border-bottom: 1px solid #f8f9fa;
  font-size: 12px;
}

.log-entry:last-child {
  border-bottom: none;
}

.timestamp {
  color: #7f8c8d;
  font-family: monospace;
  min-width: 80px;
}

.message {
  flex: 1;
}

.log-entry.info .message { color: #3498db; }
.log-entry.success .message { color: #27ae60; }
.log-entry.warning .message { color: #f39c12; }
.log-entry.error .message { color: #e74c3c; }

@media (max-width: 768px) {
  .demo-grid {
    grid-template-columns: 1fr;
  }
  
  .controls {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
